package org.abratuhi.kvngroupware.user.mptua;

import java.util.List;
import java.util.Properties;

import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.AbstractResponseMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.user.manager.UserManager;
import org.abratuhi.kvngroupware.user.model.User;
import org.jdom.Element;

public class UserResponseMessageProceeder extends AbstractResponseMessageProceeder{
	LoginManager loginmanager;
	UserManager usermanager;

	public UserResponseMessageProceeder(MessageSender sender, Properties locale, LoginManager loginmanager, UserManager usermanager){
		super(sender, locale);
		this.loginmanager = loginmanager;
		this.usermanager = usermanager;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element response = message.getRoot().getChild("response");
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		String status = response.getAttributeValue("status");

		if(type.equals("user")){
			User u = (response.getChild("user") != null) ? User.fromElement((Element) response.getChild("user")) : null;
			
			if(status.equals("ok")){
				if(action.equals("get")){
					List<Element> users = response.getChildren("user");
					usermanager.clear();
					for(int i=0; i<users.size(); i++){
						User user = User.fromElement(users.get(i));
						usermanager.put(user.getId(), user);
					}
				}
				else if(action.equals("create")){
					// TODO: ?
				}
				else if(action.equals("update")){
					usermanager.update(u.getId(), u);
				}
				else if(action.equals("delete")){
					if(u.getId().equals(loginmanager.getUser().getId())){
						// TODO ?
					}
					else{
						usermanager.remove(u.getId());
					}
				}
			}
		}
	}

}
